import Vue from 'vue'
import Router from 'vue-router'
import { constantRouterMap, asyncRouterMap, constUrl } from './routes'
import {  Notification  } from 'element-ui'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth' 
NProgress.configure({ showSpinner: false })

Vue.use(Router)
const router = new Router({
  routes: constantRouterMap,
  // routes: constUrl,
  mode: 'hash'
})

const LOGIN_PAGE_NAME = 'login'

router.beforeEach((to, from, next) => {
  NProgress.start()
  const token = getToken()
  if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: LOGIN_PAGE_NAME // 跳转到登录页
    })
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    next()
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    next({
      name: 'welcome'
    })
  } else {
    const userInfo = store.state.user.userInfo
    // 用户信息不存在，先拉取用户信息, 然后依据用户权限表动态生成左侧菜单栏
    if (!userInfo) {
      store.dispatch('getUserInfo')
      .then(res => {
        if (res.code === 1) {
          if (store.state.user.userInfo.managerType == 1) {
            console.log('router', asyncRouterMap);
            store.commit('ADD_MENUS', asyncRouterMap)
            router.addRoutes(asyncRouterMap)
            next({
              ...to, replace: true
            })
          } else {
            store.dispatch('getAuthorityMenuList')
            .then(res => {
              if (res.code == 1) {
                router.addRoutes(res.resultRoutes)
                next({
                  ...to, replace: true
                }) 
              } else {
                store.dispatch('LogOut')
                .then(() => {
                  next({
                    name: LOGIN_PAGE_NAME
                  })
                })
              }       
            })

          }      
          
        } else {
          // 拉取用户信息业务码不等于1
          Notification({
            title: '警告',
            message: res.msg,
            type: 'error'
          })
         
        }
      })
      .catch(err => {
        store.dispatch('LogOut')
        .then(() => {
          next({
            name: LOGIN_PAGE_NAME
          })
        })
      })
    } else {
      next()
    }
  }
  NProgress.done()
})

router.afterEach(() => {
  NProgress.done()
})

export default router